/***********************
* Description
*	Provides the common function.

* Dependency
* 	Container.js, Date.js, String.js, Validator.js
************************/


    /***************************************************************
        Constructor
    ****************************************************************/
function Utility(){}	


    /***************************************************************
        Public methods
    ****************************************************************/

Utility.prototype.leadingZero 		= utility_js_leadingZero
Utility.prototype.changeStyle 		= utility_js_changeStyle
Utility.prototype.alert 			= utility_js_alert;
Utility.prototype.alertV2 			= utility_js_alertV2;
Utility.prototype.goCommandButton 	= utility_js_goCommandButton;
Utility.prototype.executeValidation = utility_js_executeValidation;
Utility.prototype.closeWindow		= utility_js_closeWindow;
Utility.prototype.closeWindow2Link	= utility_js_closeWindow2Link;
Utility.prototype.submitForm		= utility_js_submitForm;
Utility.prototype.openModalWindow	= utility_js_openModalWindow;
Utility.prototype.changeWindowLocation	= utility_js_changeWindowLocation;	// <SYNC 2_IE_SESSION>
Utility.prototype.openerChangeWindowLocation	= utility_js_openerChangeWindowLocation	// <SYNC 2_IE_SESSION>
Utility.prototype.openWindow		= utility_js_openWindow;
Utility.prototype.loadParamIndexed	= utility_js_loadParamIndexed;
Utility.prototype.setIncludeParamMap	= utility_js_setIncludeParamMap;
Utility.prototype.getCallerKeyQueryString	= utility_js_getCallerKeyQueryString;
Utility.prototype.getParamIndexedQueryString	= utility_js_getParamIndexedQueryString;
Utility.prototype.getParamMapQueryString = utility_js_getParamMapQueryString;
Utility.prototype.getCommonHiddenQueryString = utility_js_getCommonHiddenQueryString;
Utility.prototype.getParamIndexed	= utility_js_getParamIndexed;
Utility.prototype.composeArgumentsArray	= utility_js_composeArgumentsArray;
Utility.prototype.goRowChange		= utility_js_goRowChange;

Utility.prototype.calcAgeFromDDMMYY = utility_js_calcAgeFromDDMMYY;
Utility.prototype.calcAge = utility_js_calcAge;

Utility.prototype.setCRStrParam		= utility_js_setCRStrParam;

Utility.prototype.submitAjaxForm= utility_js_submitAjaxForm;
Utility.prototype.goCommandButtonAjax= utility_js_goCommandButtonAjax;

//TonyKuo Modify 20110705 P-20110705-003 Start
Utility.prototype.goDisabledField= utility_js_goDisabledField;
//TonyKuo Modify 20110705 P-20110705-003 End
/**
* Construct a parameter string for crystal report object.
* @param	key		key of the crystal report parameter
* @param	value	value of the crytal report parameter
* @return	string	string of the result

*/
function utility_js_setCRStrParam(key, value){
	return "crStrParamMap("+key+")="+value;
}

/**
* Pad the leading zero.
* @param	x	the input value to be padded zero.

*/

function utility_js_leadingZero(x) { 
	var FUNCTION_NAME = "leadingZero(x)";
	var str = "";
	try {
		str = String(x).replace(/\b(\d)\b/g, '0$1');
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}			
	return str;
}

// Change the element's style class.
/**
* Change the element's style class.
* @param	element		the object.
* @param	styleName	css style name.
**/
function utility_js_changeStyle(element, styleName) {
	
	var FUNCTION_NAME = "changeStyle(element, styleName)";
	try {
		element.className = styleName;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}	
}



//Added by Hanna on 18Jul2006
/*
*	returns the remainder of m divided by n
*	@param	m	numerator
* 	@param	n	denominator
*/
function Mod(a, b) { 
	return a-Math.floor(a/b)*b;
}

// added by Victor on 20060206
/*
 * Place all the error messages in an Array in the message layer as defined by <phtml:msgLayer>
 * @param	validationLayerIndex	the index of the message layer on the current page 
 * @param	alertmessage	String of alert messages
 * @param	delimiter	a string to be appended to each element in fields array for display in the message layer
 */
function utility_js_alertV2(validationLayerIndex, alertmessage, delimiter){
		var errorArray = new Array();
		errorArray[0] = alertmessage;
		utility_js_alert(validationLayerIndex, errorArray, delimiter);
}

/**
 * Place all the error messages in an Array in the message layer as defined by <phtml:msgLayer>
 * @param	validationLayerIndex	the index of the message layer on the current page 
 * @param	fields		Javascript Array
 * @param	delimiter	a string to be appended to each element in fields array for display in the message layer
 */
function utility_js_alert(validationLayerIndex, fields, delimiter) {
	log.debug(validationLayerIndex+'/'+fillMessageLink);
	var sep = delimiter ? delimiter : '';
	if (sep.trim().length <= 0) {
//		sep = '\n'; modified by Cliff on 15-10-04
		sep = '<BR>';
	}
	//for validation presentation in layer
	var message = '';
	//get array messages

	if (fields.length > 0){
		message = fields.join(sep);
	}
	if (typeof(validationLayerIndex) != 'undefined' && 
		typeof(fillMessageLink) != 'undefined' && 
		typeof(openMessageLink) != 'undefined' && 
		validationLayerIndex && 
		fillMessageLink && 
		openMessageLink){
		if (fields.length > 0){
			message = fields.join(sep);
			//Append message to serverError ;
			if (typeof(serverError) != 'undefined' && 
				serverError.trim() && serverError.trim().length && serverError.trim().length > 0){
				message = serverError + sep + message;
			}
			//alert('message1: ' + message);
			fillMessageLink(validationLayerIndex, message);
			openMessageLink(validationLayerIndex);
		}else {
			message = '';
			//Append message to serverError ;
			if (typeof(serverError) != 'undefined' && 
				serverError.trim() && serverError.trim().length && serverError.trim().length > 0){
				message = serverError + sep + message;
			}
			//alert('message2: ' + message);
			fillMessageLink(validationLayerIndex, message);
			if (message.trim().length <= 0){
				closeMessageLink(validationLayerIndex);
			}else{
				openMessageLink(validationLayerIndex);
			}
		}
	}else{
		message = fields.join('\n');
		//Append message to serverError ;
		if (typeof(serverError) != 'undefined' && 
			serverError.trim() && serverError.trim().length && serverError.trim().length > 0){
			message = serverError + '\n' + message;
		}
		if (fields.length > 0){
			//alert('message3: ' + message);
			alert(message);
		}
	}
}

/* 
 * Is replaced by closeWindow2Link().
 * Note: isFieldChanges() JavaScript is generated by PJFormCOntrolsTag.java
 * @param confirmOnClose	need any confirmation dialog? 
 * @param confirmMessage	message to be used in confirmation dialog
 * @param newRecordModeValue	the value to be checked if the form is in new record mode.
 * @author	Hanna 10Nov2004
 */
function utility_js_closeWindow(confirmOnClose, confirmMessage, newRecordModeValue){
	var close = true;//, confirmOnClose = true;
	
	if (confirmOnClose == true)
		if (isFieldChanges(document.forms[formName]) ||//have changes
			document.forms[formName]['recordMode'].value.toString().equalsIgnoreCase(newRecordModeValue)){//is NEW
			close = false;
		}
	if (close  == false && confirmOnClose == true)	close = confirm(confirmMessage);
	if (close == true){
		try{
			opener.window.focus();
		}catch(E){}
		window.close();
	}
}

/* 
 * To be called by Close button.
 * It choose to close the page by jumping back the winlink or close the window directly if winlink is not specified.
 * It also supports to choose jumping back the winlink with target option i.e. self or parent (applicable to frame)
 * @param winlink		Original url in the window 
 * @param confirmOnClose	need any confirmation dialog? 
 * @param confirmMessage	message to be used in confirmation dialog
 * @param newRecordModeValue	the value to be checked if the form is in new record mode.
 * @param linkTarget		target url of the window
 * @author	Eddy 19/12/2005 10:31
 */
//function utility_js_closeWindow2Link(winlink, confirmOnClose, confirmMessage, newRecordModeValue){
function utility_js_closeWindow2Link(winlink, confirmOnClose, confirmMessage, newRecordModeValue, linkTarget){//Modiifed by Hanna on 28Mar2006
	var close = true;//, confirmOnClose = true;
	
	//edit by Sam 20110113
	if (confirmOnClose == true){
		if (isFieldChanges(document.forms[formName]) ||//have changes
			document.forms[formName]['recordMode'].value.toString().equalsIgnoreCase(newRecordModeValue)){//is NEW
			close = false;
		}
	}
	if (close  == false && confirmOnClose == true)	close = confirm(confirmMessage);
	if (close == true)	{
		//added by eddy on 18Aug2006
		try{
			showLoading();
		} catch (e){}
		
		//Added by Hanna on 28Mar2006
		// check if the target is itself
		if (linkTarget && linkTarget.equalsIgnoreCase('self')){
			window.location = encodeURI(appendWindowName(winlink));	//<SYNC 2_IE_SESSION>
		}else if (linkTarget && linkTarget.equalsIgnoreCase('parent')){
			if (parent){
				parent.location.href = encodeURI(appendWindowName(winlink));	//<SYNC 2_IE_SESSION>
			}else{
				window.location = encodeURI(appendWindowName(winlink));	//<SYNC 2_IE_SESSION>
			}
		}else{
			window.location = encodeURI(appendWindowName(winlink));	//<SYNC 2_IE_SESSION>
		}
	}
}

var utiity_submitted = false;
/* 
 * The trigger point for each button, which is supposed to 
 * 1. validate the form, 
 * 2. ask confirmation
 * 3. submit form.
 * You can control the behaviour by setting parameters.
 * 
 * For other buttons that do complicate things before submisssion or 
 * just do client-side javascript logic, please tailor made function.
 * 
 * @param	formName		the name of the form
 * @param	cmdName			the property name that holds the command value e.g. command
 * @param	cmdValue		the value of the command e.g. 21 for saving. Reference: ReFormConstants.java
 * @param	exeValidation	Do validation before submission??
 *							if null, it means true.
 * @param	confirmOnSubmit	Need to prompt user for confirmation before form submission??
 *							if null, it means true.
 * @param	confirmMessage	the confirmation message
 * @param	turnUnProtectOn	Need to unprotect the form before form submission?? 
 *							if null, it means true.
 * @author	Hanna	12Nov2004
 */
function utility_js_submitForm(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn){
		return this.goCommandButton(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn);
}


/*
//store the original onclick, onselect event
var origOnFocus = window.onfocus;
var origDocOnClick = window.document.onclick;
var origDocOnDBLClick = window.document.ondblclick;
var origOnSelect = window.onselectstart;

var origDocMouseDown = window.document.onmousedown;
var origDocMouseOver = window.document.onmouseover;
*/

/*
 * Open a window with modal control. i.e user cannot click on parent window without closing the newly open window.
 * @param popupsite		String that specifies the URL of the document to display.
 * @param windowname	String that specifies the name of the window. 
 * @param width			Sets the width of the window, in pixels. The minimum value is 100.
 * @param height		Specifies the height of the window, in pixels. The minimum value is 100.
 * @param screenX		Sets the position of the window in pixels from the left of the screen in Netscape 4+. 
 * @param screenY		Sets the position of the window in pixels from the top of the screen in Netscape 4+. 
 * @param left			Sets the position of the window in pixels from the left of the screen in IE 4+. This value is relative to the upper-left corner of the screen. The value must be greater than or equal to 0. 
 * @param top			Sets the position of the window in pixels from the top of the screen in IE 4+. This value is relative to the upper-left corner of the screen. The value must be greater than or equal to 0.
 * @param toolbar		Not used. (All screens should not have toolbar)
 * @param scrollYN		Specifies whether to display horizontal and vertical scroll bars. The default is 1.
 * @param status		Specifies whether to add a status bar at the bottom of the window. The default is yes.
 * @param menubar		Specifies whether to display the menu bar. The default is 0.
 * @param resizable		Specifies whether to display resize handles at the corners of the window. The default is 1.
 */
function utility_js_openModalWindow(popupsite, windowname, width, height, screenX, screenY, left, top, toolbar, scrollYN, status, menubar, resizable) {
	var FUNCTION_NAME = "openModalWindow()";
	try{
		if (screenX == null)	screenX = '10';
		if (screenY == null)	screenY = '10';
		if (left == null)		left = '10';
		if (top == null)		top = '10';
		if (toolbar == null)	toolbar = '0';
		if (scrollYN == null)	scrollYN = '1';
		if (status == null)		status = 'yes';
		if (menubar == null)	menubar = '0';
		if (resizable == null)	resizable = '1';

		var events = this.getWindowEvent();//Hanna added 31Mar2005 run-time get window event instead of page onload
		var loginId = document[formName].loginId.value;
		popupsite = appendWindowName(popupsite); // <SYNC 2_IE_SESSION> appendWindowName defined in function.js			
		popupsite = appendPopWin(popupsite); // 2010.11.27; Victor;
		
		var childwindow = window.open(popupsite, windowname+loginId,"left=" + left + "screenX=" + screenX + "screenY=" + screenY + ",top=" + top + ",toolbar=0,scrollbars=" + scrollYN + ",status=" + status +",menubar=" + menubar + ",resizable=" + resizable + ", height=" + height + ",width=" + width);

		window.document.onclick = function(){
			if (childwindow.closed == false){
				try{
					//parent.window.blur();
					isOnFocus=false;
				}catch(E){}
				
				childwindow.focus();
			}
			if (childwindow.closed == true){

				//START: Hanna added 31Mar2005 run-time get window event instead of page onload
				window.document.onclick = events[1];
				window.document.ondblclick = events[2];
				window.onfocus = events[0];
				window.onselectstart = events[3];

				window.document.onmousedown = events[4];
				window.document.onmouseover = events[5];
				//END: Hanna added 31Mar2005

				if (typeof(containerUtils) != 'undefined' && containerUtils.unprotectSelectBox)	containerUtils.unprotectSelectBox();
				new LayerContainer().place(null, 'floater', 0, 0, 0, screen.availWidth, screen.availHeight);
			}
		};
		window.document.ondblclick = window.document.onclick;
		window.onfocus = window.document.onclick;
		window.onselectstart = window.document.onclick;

		window.document.onmousedown = window.document.onclick;
		//window.document.onmouseover = window.document.onclick;
		if (typeof(containerUtils) != 'undefined' && containerUtils.protectSelectBox)	containerUtils.protectSelectBox();
		new LayerContainer().place(null, 'floater', 1, 0, 0, screen.availWidth, screen.availHeight);

		childwindow.focus();
		return childwindow;
	} catch (e){
		//alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
		alert("Warning: Please enable the pop-up settings for PolyJ.");
	}
}
/**
* Opens a new window and loads the document specified by a given URL.
* @param	popupsite		URL to open
* @param	windowname	name of the window
* @param	width		width of the window in pixel
* @param	height		height of the window in pixel
* @param	screenX		X position of the window (for Navigator)
* @param	screenY		Y position of the window (for Navigator)
* @param	left			left position of the window (for IE)
* @param	top			top position of the window (for IE)
* @param	toolbar		Specifies whether to display the menu bar
* @param	scrollYN		Specifies whether to display horizontal and vertical scroll bars
* @param	status		Specifies whether to add a Status Bar at the bottom of the window
* @param	menubar		Specifies whether to display the menu bar
* @param	resizable		Specifies whether to display resize handles at the corners of the window.
* @return	window		the opened window reference.
**/
function utility_js_openWindow(popupsite, windowname, width, height, screenX, screenY, left, top, toolbar, scrollYN, status, menubar, resizable) {
	var FUNCTION_NAME = "openWindow()";
	try{
		if (screenX == null)	screenX = '10';
		if (screenY == null)	screenY = '10';
		if (left == null)		left = '10';
		if (top == null)		top = '10';
		if (toolbar == null)	toolbar = '0';
		if (scrollYN == null)	scrollYN = '1';
		if (status == null)		status = 'yes';
		if (menubar == null)	menubar = '0';
		if (resizable == null)	resizable = '1';

		var loginId = document[formName].loginId.value;
		popupsite = appendWindowName(popupsite); // <SYNC 2_IE_SESSION> appendWindowName defined in function.js
		popupsite = appendPopWin(popupsite); // 2010.11.27; Victor;
		var childwindow = window.open(popupsite, windowname+loginId,"left=" + left + "screenX=" + screenX + "screenY=" + screenY + ",top=" + top + ",toolbar=0,scrollbars=" + scrollYN + ",status=" + status +",menubar=" + menubar + ",resizable=" + resizable + ", height=" + height + ",width=" + width);

		childwindow.focus();
		return childwindow;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}




/* 
 * It composes query string by using specified paramIndexed array and paramMap (key,-value pair)
 * If no paramIndexed is specified, try to find call getParamIndexed() to get form.paramIndexed array.
 * @param paramIndexed	array	an array of paramIndexed data for composing the query string.
 * @return			string	a string of pair-value delimited by '&' i.e. query string.
 */
function utility_js_getParamIndexedQueryString(paramIndexed){
	var FUNCTION_NAME = "getParamIndexedQueryString()";
	if (typeof(this.once) == 'undefined' || this.once == null)	this.once = true;
	if (typeof(this.paramMapInclude) == 'undefined' || this.paramMapInclude == null)	this.paramMapInclude = true;
	var queryString = '';
	try{
		if (paramIndexed != null && paramIndexed.length){
			var x;
			for (x=0; x<paramIndexed.length; x++){
				queryString += (x > 0 ? '&' : '') + 'paramIndexed[' + x + ']='+paramIndexed[x];
			}
		}else{//try to initialize
			//check if this function is already called.
			if (this.once){
				this.getParamIndexed();
				var form = document.forms[formName];
				this.once = false;
				return this.getParamIndexedQueryString(form.paramIndexed);
			}
		}
		if (this.paramMapInclude != null && this.paramMapInclude == false){
			;
		}else{
			var paramMapQueryString = this.getParamMapQueryString();
			if (paramMapQueryString.length > 0){
				queryString += '&' + this.getParamMapQueryString();
			}
		}
		return queryString;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
		return '';
	}
}

// Added by Betty 25/3/2006
/* 
 * It composes query string by using specified paramIndexed array and paramMap (key,-value pair).
 * If no paramIndexed is specified, try to find call getParamIndexed() to get form.paramIndexed array.
 * @param paramIndexed	array	an array of paramIndexed data for composing the query string.
 * @return			string	a string of pair-value delimited by '&' i.e. query string.
 */
function utility_js_getCallerKeyQueryString(paramIndexed){
	var FUNCTION_NAME = "getCallerKeyQueryString()";
	if (typeof(this.once) == 'undefined' || this.once == null)	this.once = true;
	if (typeof(this.paramMapInclude) == 'undefined' || this.paramMapInclude == null)	this.paramMapInclude = true;
	var queryString = '';
	try{
		if (paramIndexed != null && paramIndexed.length){
			var x;
			for (x=0; x<paramIndexed.length; x++){
				queryString += (x > 0 ? '/' : '') + paramIndexed[x];
			}
		}else{//try to initialize
			//check if this function is already called.
			if (this.once){
				this.getParamIndexed();
				var form = document.forms[formName];
				this.once = false;
				return this.getCallerKeyQueryString(form.paramIndexed);
			}
		}
		if (this.paramMapInclude != null && this.paramMapInclude == false){
			;
		}else{
			var paramMapQueryString = this.getParamMapQueryString();
			if (paramMapQueryString.length > 0){
				queryString += '&' + this.getParamMapQueryString();
			}
		}
		return queryString;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
		return '';
	}
}
// Betty 25/3/2006 End



/* 
 * Not Used in PolyJF!!!
 * Assume the calling page has defined 
 * 1. curTabName variable
 * 2. changeIFrameLocation function
 * When the master table's row changes, this method will call changeIFrameLocation(curTarget)
 * in order to change location of corresponding iframe location.
 * Logic: 
 * 1. goRowChange() will be passed a set of record key.
 * 2. row changes criteria is checked.
 * 2. if so, load the record key into the form.paramIndexed[N], where N is 0 to 10 (i.e. support record key of 11 size)
 * 3. assign form.paramIndexed array with the set of record key
 * 4. call changeIFrameLocation(curTabName) to change iframe location
 * @param arguments	a list of record key.
 */
function utility_js_goRowChange(){
	var FUNCTION_NAME = "goRowChange()";
	try{
		var arguArray = this.composeArgumentsArray(arguments);
		var paramIndexed = this.getParamIndexed();
		if (!new Validator().isArrayEquals(paramIndexed, arguArray)){

			var office, dept, cls, agt, year, id, sec, endst, seq, key9, key10;
			if (arguments.length > 0) office = arguments[0];
			if (arguments.length > 1) dept = arguments[1];
			if (arguments.length > 2) cls = arguments[2];
			if (arguments.length > 3) agt = arguments[3];
			if (arguments.length > 4) year = arguments[4];
			if (arguments.length > 5) id = arguments[5];
			if (arguments.length > 6) sec = arguments[6];
			if (arguments.length > 7) endst = arguments[7];
			if (arguments.length > 8) seq = arguments[8];
			if (arguments.length > 9) key9 = arguments[9];
			if (arguments.length > 10) key10 = arguments[10];
			this.loadParamIndexed(office, dept, cls, agt, year, id, sec, endst, seq, key9, key10);
			if (typeof(changeIFrameLocation) != 'undefined' &&
				typeof(curTabName) != 'undefined'				){
				changeIFrameLocation(curTabName);
			}
			return true;
		}
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
	return false;
}

/* 
 * Calculate the age for the specified date object.
 * @param dataObj	date object
 */
function utility_js_calcAge(dateObj){
	
	var FUNCTION_NAME = "calcAge(dd, mm, yy)";
	var age = 0;
	try{
		age = this.calcAgeFromDDMMYY(dateObj.getDate(), dateObj.getMonth()+1, dateObj.getFullYear());
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
	return age;
}

/*
 * Calculate the age for the specified day, month and year
 * @param dd	day
 * @param mm	month
 * @param yy	year
 */
function utility_js_calcAgeFromDDMMYY(dd, mm, yy){
	
	var FUNCTION_NAME = "calcAge(dd, mm, yy)";
	var age = 0;
	var validDate = true;
	try{

		if ((mm<1) || (mm>12) || (dd<1) || (dd>31) || (yy<1) ||(mm=="") || (dd=="") || (yy==""))  
			validDate=false;
		else 
			if (((mm==4) || (mm==6) || (mm==9) || (mm==11)) && (dd>30))
				validDate=false;
			else if (mm==2) {
				if (dd>29)
					validDate=false;
				else if((dd>28) && (!(((yy%4==0) && (yy%100!=0)) || (yy%400==0))))   
					validDate=false;
			}
		else if((yy>9999)||(yy<0)) 
			validDate=false;

		if(validDate==true) {
			days = new Date()
			gdate = days.getDate()
			gmonth = days.getMonth()
			gyear = days.getYear()
			age=gyear-yy;
			if((mm==(gmonth+1))&&(dd<=parseInt(gdate))) {
				age=age; 
			} else {
				if(mm<=(gmonth)) {
					age=age;
				} else {
					age=age-1 ;
				} 
			}
			if(age==0)
			age=age;
		}
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
	return age;
}


/*
 * Trim the spaces starting from the left of the string
 * @param str	String to be trimmed
 * @return  	String trimmed
 
 */


Utility.prototype.leftTrim = utility_js_leftTrim;
function utility_js_leftTrim(str){
	return str.replace(new RegExp("^[\\s]+", "gm"), "");
}

/*
 * Trim the spaces starting from the right of the string
 * @param str	String to be trimmed
 * @return  	String trimmed
 
 */
Utility.prototype.rightTrim = utility_js_rightTrim;
function utility_js_rightTrim(str){
	return str.replace(new RegExp("[\\s]+$", "gm"), "") ;
}

/*
* Tests if this string starts with the specified prefix.
* @param	prefix	the prefix
* @return	true: if the string starts with the parameter suffix; false: otherwise.
*/
Utility.prototype.startsWith = utility_js_startsWith;
function utility_js_startsWith(str, str1){
	return (str.match("^"+str1)==str1);
}


    /***************************************************************
        Private methods
    ****************************************************************/

/* 
 * This is a private function to be called by submitForm().
 * The trigger point for each button, which is supposed to 
 * 1. validate the form, 
 * 2. ask confirmation
 * 3. submit form.
 * You can control the behaviour by setting parameters.
 * 
 * For other buttons that do complicate things before submisssion or 
 * just do client-side javascript logic, please tailor made function.
 * 
 * @param	formName		the name of the form
 * @param	cmdName			the property name that holds the command value e.g. command
 * @param	cmdValue		the value of the command e.g. 21 for saving. Reference: ReFormConstants.java
 * @param	exeValidation	Do validation before submission??
 *							if null, it means true.
 * @param	confirmOnSubmit	Need to prompt user for confirmation before form submission??
 *							if null, it means true.
 * @param	confirmMessage	the confirmation message
 * @param	turnUnProtectOn	Need to unprotect the form before form submission?? 
 *							if null, it means true.
 * @author	Hanna	12Nov2004
 */
function utility_js_goCommandButton(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn){
	if (utiity_submitted == false){
		utiity_submitted = true;

		var FUNCTION_NAME = "goCommandButton()";
		if (exeValidation == null)		exeValidation = true;
		if (confirmOnSubmit == null)	confirmOnSubmit = true;
		if (turnUnProtectOn == null)	turnUnProtectOn = true;
		// TonyKuo Modify 20110705 P-20110705-003 Start
		var disableSaveBtnQug = false;
		var disableSaveBtnPol = false;
		// TonyKuo Modify 20110705 P-20110705-003 End
		
		try{
			var form = document.forms[formName];
			
			// TonyKuo Modify 20110705 P-20110705-003 Start
			if(formName != null){
				if(formName == 'qugMotDetailForm'){
					disableSaveBtnQug = true;
				}
				
				if(formName == 'polMotDetailForm'){
					disableSaveBtnPol = true;
				}
				this.goDisabledField(true, disableSaveBtnQug, disableSaveBtnPol);
			}
			// TonyKuo Modify 20110705 P-20110705-003 End
						
			var submit = true;
			if (form){
				var field = form[cmdName];
				//1. do the validation by calling function generated by <html:javascript>
				if (exeValidation == true){
					try{
						window.status = 'Start validation....';
						submit = this.executeValidation(formName);
						window.status = 'Please see validation message....';
					}catch (e){
						alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: executeValidation()");
						// TonyKuo Modify 20110705 P-20110705-003 Start
						this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
						// TonyKuo Modify 20110705 P-20110705-003 End
					}
				}
				//2a. if error, don't continue
				if (submit == false) {
					utiity_submitted = false; // Cliff Added 23Jul2005 for reset flag for next submition
					// TonyKuo Modify 20110705 P-20110705-003 Start
					this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
					// TonyKuo Modify 20110705 P-20110705-003 End
					return false;
				}
				//2b. if no error, check confirmOnSubmit
				if (confirmOnSubmit == true){
					submit = confirm(confirmMessage);
					window.status = '';
				}
				if (submit == true){
					//3. un-protect the all form elements before form submit
					if (turnUnProtectOn){
						try{
							window.status = 'Prepare form submission....';
							//Commented by Hanna on 10Nov2006
							//if (containerUtils && containerUtils.unprotectAll)	containerUtils.forceUnProtectAll();//containerUtils.unprotectAll();
							if (disabledElementMap ){
								var keys = disabledElementMap.keys();
								//alert('keys:' + keys.join (','));
								if (keys){
									for (var k=0; k<keys.length;k++ ){
										containerUtils.enable(keys[k]);
									}
								}
							}
						// TonyKuo Modify 20110705 P-20110705-003 Start
						this.goDisabledField(true, disableSaveBtnQug, disableSaveBtnPol);
						// TonyKuo Modify 20110705 P-20110705-003 End
						}catch (e){
							alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: unprotectAll()");
							// TonyKuo Modify 20110705 P-20110705-003 Start
							this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
							// TonyKuo Modify 20110705 P-20110705-003 End
							return false;
						}
					}
					//4. assign command value
					if (field && field.value){
						field.value = cmdValue;
						if (log)	log.debug('cmdName='+cmdName+'/cmdValue='+ cmdValue);
					}
					//5. submit the form
					try{
						window.status = 'Start form submission....';
						form.submit();									
					}catch (e){
						alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: submit the form");
						// TonyKuo Modify 20110705 P-20110705-003 Start
						this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
						// TonyKuo Modify 20110705 P-20110705-003 End
						return false;
					}
				}
				else {
					utiity_submitted = false; // Cliff Added 21Jul2005 for reset flag for next submition
					// TonyKuo Modify 20110705 P-20110705-003 Start
					this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
					// TonyKuo Modify 20110705 P-20110705-003 End
					return false;
				}
			}
		} catch (e){
			alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
			// TonyKuo Modify 20110705 P-20110705-003 Start
			this.goDisabledField(false, disableSaveBtnQug, disableSaveBtnPol);
			// TonyKuo Modify 20110705 P-20110705-003 End
			return false;
		}
		window.status = '';
		return true;

	}
	alert('Request is processing.');
	return false;
}

/*
 * Disabled Quotation, Policy Save Button on Click this
 */
function utility_js_goDisabledField(disabled, disableSaveBtnQug, disableSaveBtnPol){
	if(disableSaveBtnQug){
		containerUtils.setDisabled('save', disabled);
		containerUtils.setDisabled('nextStep', disabled);
	}
	
	if(disableSaveBtnPol){
		containerUtils.setDisabled('save', disabled);
	}
}

/**
  * For Ajax Page Submit  
**/
function utility_js_submitAjaxForm(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn){
		return this.goCommandButtonAjax(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn);
}

function utility_js_goCommandButtonAjax(formName, cmdName, cmdValue, exeValidation, confirmOnSubmit, confirmMessage, turnUnProtectOn){
	if (utiity_submitted == false){
		utiity_submitted = true;

		var FUNCTION_NAME = "goCommandButton()";
		if (exeValidation == null)		exeValidation = true;
		if (confirmOnSubmit == null)	confirmOnSubmit = true;
		if (turnUnProtectOn == null)	turnUnProtectOn = true;
		try{
			var form = document.forms[formName];
			var submit = true;
			if (form){
				var field = form[cmdName];
				//1. do the validation by calling function generated by <html:javascript>
				if (exeValidation == true){
					try{
						window.status = 'Start validation....';
						submit = this.executeValidation(formName);
						window.status = 'Please see validation message....';
					}catch (e){
						alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: executeValidation()");
					}
				}
				//2a. if error, don't continue
				if (submit == false) {
					utiity_submitted = false; // Cliff Added 23Jul2005 for reset flag for next submition
					return false;
				}
				//2b. if no error, check confirmOnSubmit
				if (confirmOnSubmit == true){
					submit = confirm(confirmMessage);
					window.status = '';
				}
				if (submit == true){
					//3. un-protect the all form elements before form submit
					if (turnUnProtectOn){
						try{
							window.status = 'Prepare form submission....';
							//Commented by Hanna on 10Nov2006
							//if (containerUtils && containerUtils.unprotectAll)	containerUtils.forceUnProtectAll();//containerUtils.unprotectAll();
							if (disabledElementMap ){
								var keys = disabledElementMap.keys();
								//alert('keys:' + keys.join (','));
								if (keys){
									for (var k=0; k<keys.length;k++ ){
										containerUtils.enable(keys[k]);
									}
								}
							}
						}catch (e){
							alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: unprotectAll()");
							return false;
						}
					}
					//4. assign command value
					if (field && field.value){
						field.value = cmdValue;
						if (log)	log.debug('cmdName='+cmdName+'/cmdValue='+ cmdValue);
					}
					//5. submit the form
					try{
						window.status = 'Start form submission....';
						//20080825 Karen
						//form.submit();
						retrieveResult("theTable", "thePagePagination", "thePagePagination2");				
					}catch (e){
						alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: submit the form");
						return false;
					}
				}
				else {
					utiity_submitted = false; // Cliff Added 21Jul2005 for reset flag for next submition
					return false;
				}
			}
		} catch (e){
			alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
			return false;
		}
		window.status = '';
		utiity_submitted = false;   //20080826 Because Ajax,it can't initialize utiity_submitted value by refresh
		return true;

	}
	alert('Request is processing.');
	return false;
}

/* 
 * This is a private function to be called by sumbitForm()
 * Execute the validation by calling function generated by <html:javascript>
 * @param	formName	the form name 
 * @param	boolean		validation result returned by the validation function.
 */
function utility_js_executeValidation(formName){
	var FUNCTION_NAME = "executeValidation()";
	try{
		var validateFunction = eval('validate'+ formName.upperFirstLetter());//by reflection
		if (log && validateFunction != null)	log.debug(validateFunction.toString());
		//return validateFunction(document.forms[formName]);
		var funcArguments = new Array(document.forms[formName]);
		return validateFunction.apply(this, funcArguments);
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}
    
//START: Hanna added 31Mar2005 run-time get window event instead of page onload
/*
 * This is a private function to be called by openModalWindow().
 * It gets window event in run-time.
 */
Utility.prototype.getWindowEvent	= utility_js_getWindowEvent;
function utility_js_getWindowEvent() {
	//store the original onclick, onselect event
	//window.status = 'getWindowEvent';
	var events = new Array();
	events[0] = window.onfocus;
	events[1] = window.document.onclick;
	events[2] = window.document.ondblclick;
	events[3] = window.onselectstart;

	events[4] = window.document.onmousedown;
	events[5] = window.document.onmouseover;
	return events;
}
//END: Hanna added 31Mar2005

/* 
 * It is a private function to be called by getParamIndexedQueryString().
 * It tries to find 'paramIndexed[N]' in the current form and put the value inside an array.
 * Then assign this array to the form's paramIndexed variable for easy data manipulation.
 * @return	array	an array of the extracted data.
 */
function utility_js_getParamIndexed(){
	var FUNCTION_NAME = "getParamIndexed()";
	try{
		var form = document.forms[formName];
		var paramIndexed = new Array();
		var x = 0;
		while (true){
			var field = form['paramIndexed['+x+']'];
			if (field == null)	break;
			if (field){
				paramIndexed[x] = field.value;
			}
			x++;
		}
		form.paramIndexed = paramIndexed;
		return form.paramIndexed;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}

/* 
 * It is a private function to be called by goRowChange().
 * Load any arguments of this function into 'paramIndexed[N]' of the current form.
 * Also, put the argument values into an array.
 * @param arguments	a list of argument passed into the function.
 * @return	an array of the argument data.
 */
function utility_js_loadParamIndexed(){
	var FUNCTION_NAME = "loadParamIndexed()";
	try{
		var form = document.forms[formName];
		var paramIndexed = new Array();
		var x;
		for (x=0; x<arguments.length; x++){
			var field = form['paramIndexed['+x+']'];
			if (field){
				field.value = arguments[x];
				paramIndexed[x] = field.value;
			}
		}

		log.debug('paramIndexed='+paramIndexed);
		form.paramIndexed = paramIndexed;

	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}
    
/* 
 * It is a private function to be called by getParamIndexedQueryString() or getCallerKeyQueryString().
 * It tries to find all keys inside paramMapKeyArray and compose the query string.
 * @return	string	query string for paramMap in the current form
 */
function utility_js_getParamMapQueryString(){
	var FUNCTION_NAME = "getParamMapQueryString()";
	var queryString = '';
	//paramMapKeyArray
	try{
		if (typeof(paramMapKeyArray) != 'undefined' && paramMapKeyArray.length){
			var form = document.forms[formName];
			var x;
			for (x=0; x<paramMapKeyArray.length; x++){
				if (form[paramMapKeyArray[x]] != null){
					queryString += (x > 0 ? '&' : '') + paramMapKeyArray[x] + '='+ form[paramMapKeyArray[x]].value;
				}
			}
		}
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
	return queryString;
}
    
/* 
 * It is a private function to be called by getParamIndexedQueryString() or getCallerKeyQueryString().
 * It tries to find all keys inside paramMapKeyArray and compose the query string.
 * @return	string	query string for paramMap in the current form
 */
function utility_js_getCommonHiddenQueryString(){
	var FUNCTION_NAME = "getCommonHiddenQueryString()";
	var queryString = '';
	var hiddens = new Array(
		//Please add common hidden fields that needs to be passed screen by screen
		/* 
		 * Please sync with AbstractMgrNode.getCommonMgrQueryString()
		 */
		'crossTarget',
		'submitFrom',
		'popWin'
		);
	try{

		var form = document.forms[formName];
		for (x=0; x<hiddens.length; x++){
			if (form[hiddens[x]] != null){
				queryString += (x > 0 ? '&' : '') + hiddens[x] + '='+ form[hiddens[x]].value;
			}
		}
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
	return queryString;
}

/*
 * This is a private function to be called by getParamIndexedQueryString();
 * This is to set the indicator to include paramMap when composing paramIndexed query string.
 */
function utility_js_setIncludeParamMap(paramMapInclude){
	this.paramMapInclude = paramMapInclude;
}

/* 
 * It is a private function to be called by goRowChange().
 * It composes an array with the data same as the specfieid input Array, which should be function's arguments object.
 * @param inputArray	the 'arguments' variable of function.
 * @return	array		an array of extracted data.
 */
function utility_js_composeArgumentsArray(inputArray){
	var FUNCTION_NAME = "composeArgumentsArray()";
	var array = new Array();
	try{
		var x;
		if (inputArray.length){
			for (x=0; x<inputArray.length; x++){
				array[x] = inputArray[x];
			}
		}
		return array;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}

/* 
 * FGIS - Replace with window.location	 <<SYNC 2_IE_SESSION>>
 * 
 * @param urlStr
 * @return	array		an array of extracted data.
 */
function utility_js_changeWindowLocation(urlStr){
	var FUNCTION_NAME = "utility_js_changeWindowLocation(urlStr)";
	try{
		if ( urlStr.indexOf("?") == -1 ){
			urlStr = urlStr + "?";
		} else {
			urlStr = urlStr + "&";
		}	
		urlStr = urlStr + "jsWindowName=" + getJsWindowName();
		
		window.location = urlStr;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}
/* 
 * FGIS - Replace with opener.window.location	 <<SYNC 2_IE_SESSION>>
 * 
 * @param urlStr
 * @return	array		an array of extracted data.
 */
function utility_js_openerChangeWindowLocation(urlStr){
	var FUNCTION_NAME = "utility_js_changeWindowLocation(urlStr)";
	try{
		if ( urlStr.indexOf("?") == -1 ){
			urlStr = urlStr + "?";
		} else {
			urlStr = urlStr + "&";
		}	
		urlStr = urlStr + "jsWindowName=" + getJsWindowName();
		
		opener.window.location = urlStr;
	} catch (e){
		alert("Javascript Exception [" + this.FILE_NAME + ", " + FUNCTION_NAME + "]: [" + e.name+":"+e.message+"].");		
	}
}

    /***************************************************************
        Private Constant
    ****************************************************************/

Utility.prototype.FILE_NAME="Utility.js";
document.write('<script src="/javascript/ContainerUtils.js"></script>');
